package com.sikulifang.bank.simulation.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Entity;
import com.sikulifang.bank.simulation.service.IBankConfigService;
import com.sikulifang.bank.simulation.util.DataUtil;
import com.sikulifang.bank.simulation.util.R;
import com.sikulifang.frequency.core.FrequencyContext;
import com.sikulifang.frequency.domain.FrequencyProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * ClassName BankConfigServiceImpl
 * Description 银行配置
 *
 * @author Yat
 * Date 2023年6月18日, 0018 9:37
 * version 1.0
 */
@Slf4j
@Service
public class BankConfigServiceImpl extends ServiceImpl implements IBankConfigService {

    @Override
    public R<String> saveUpdate(Entity entity) {
        R<String> result = super.saveUpdate(entity);

        updateRules(entity);
        return result;
    }

    /**
     * Description: 修改限流配置
     * <p>
     * Date: 2023年6月18日, 0018 15:34
     */
    private void updateRules(Dict dict) {
        Entity result = DataUtil.toUnderlineCase(dict);
        // 银行的code
        String bankCode = StrUtil.split(result.getStr("bank_name"), StrPool.DASHED).get(0);

        FrequencyContext.createInstance(bankCode, getFrequencyProperties(result));
    }
    private FrequencyProperties getFrequencyProperties(Dict entity) {
        FrequencyProperties frequencyProperties = new FrequencyProperties();
        frequencyProperties.setMode(entity.get("mode", 4));

        frequencyProperties.setQueryInterval(entity.get("query_interval", 0) == 0);
        frequencyProperties.setQueryDelayTime(entity.getLong("query_delay_time"));
        frequencyProperties.setQueryWaitingTime(entity.getLong("query_waiting_time"));

        frequencyProperties.setTradeInterval(entity.get("trade_interval", 0) == 0);
        frequencyProperties.setTradeDelayTime(entity.getLong("trade_delay_time"));
        frequencyProperties.setTradeWaitingTime(entity.getLong("trade_waiting_time"));

        frequencyProperties.setInterval(entity.get("interval", 0) == 1);
        frequencyProperties.setIntervalTime(entity.getLong("interval_time"));

        return frequencyProperties;
    }

    @Override
    public List<String> getQueryCriteria() {
        return ListUtil.toList("bank_name", "interface_type", "interface_name");
    }

}
